package org.damocode.iot.core.message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

/**
 * @Author: zzg
 * @Date: 2022/7/19 15:30
 * @Version: 1.0.0
 */
public enum PayloadType {

    JSON {
        public Object read(ByteBuf byteBuf) {
            return com.alibaba.fastjson.JSON.parse(byteBuf.toString(StandardCharsets.UTF_8));
        }

        public ByteBuf write(Object data) {
            if (!(data instanceof String)) {
                data = com.alibaba.fastjson.JSON.toJSONString(data);
            }

            return Unpooled.wrappedBuffer(String.valueOf(data).getBytes());
        }
    },
    STRING {
        public String read(ByteBuf byteBuf) {
            return byteBuf.toString(StandardCharsets.UTF_8);
        }

        public ByteBuf write(Object data) {
            if (!(data instanceof String)) {
                data = com.alibaba.fastjson.JSON.toJSONString(data);
            }

            return Unpooled.wrappedBuffer(String.valueOf(data).getBytes());
        }
    },
    BINARY {
        public byte[] read(ByteBuf byteBuf) {
            return ByteBufUtil.getBytes(byteBuf);
        }

        public ByteBuf write(Object data) {
            return data instanceof byte[] ? Unpooled.wrappedBuffer((byte[])((byte[])data)) : Unpooled.wrappedBuffer(String.valueOf(data).getBytes());
        }
    },
    HEX {
        public String read(ByteBuf byteBuf) {
            return ByteBufUtil.hexDump((byte[])((byte[])BINARY.read(byteBuf)));
        }

        public ByteBuf write(Object data) {
            try {
                String hex;
                if (data instanceof byte[]) {
                    hex = new String((byte[])((byte[])data));
                } else if (data instanceof char[]) {
                    hex = new String((char[])((char[])data));
                } else if (data instanceof ByteBuf) {
                    hex = new String(ByteBufUtil.getBytes((ByteBuf)data));
                } else {
                    hex = String.valueOf(data);
                }

                return Unpooled.wrappedBuffer(ByteBufUtil.decodeHexDump(hex.replace("\n", "").replace(" ", "")));
            } catch (Throwable var3) {
                throw var3;
            }
        }
    };

    PayloadType() {
    }

    public abstract ByteBuf write(Object var1);

    public abstract Object read(ByteBuf var1);

    public String getName() {
        return this.name();
    }

    public String getId() {
        return this.name();
    }

}
